package cn.com.winning.ecare.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.winning.ecare.common.Grideviewmenu;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.model.AnswerEntity;
import cn.com.winning.ecare.model.SubjectEntity;
import cn.com.winning.ecare.utils.DisplayUtil;
import cn.com.winning.ecare.utils.FilpperCallback;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.MyViewFilpper;
import cn.com.winning.ecare.utils.SlidingLayout;
import cn.com.winning.ecare.utils.URLUtils;
import cn.com.winning.ecare.utils.UserRecord;
import cn.com.winning.ecare.widgets.CustomProgressDialog;

/**
 * 满意度调查
 * @author Administrator
 *
 */
public class Process extends Activity implements FilpperCallback, OnClickListener
{
	/**
	 * 统计用到的成员变量
	 */
	private int progressValue = 0;
	private int totalSubjectCount = 0;
	private int hadAnsweredCount = 0;
	private int currentSubjectLocation = 0;

	/**
	 * 因跨成员方法使用数据而设置的组件引用
	 */
	private ProgressBar progressBar = null;
	private MyViewFilpper subjectFilpper = null;
	private List<SubjectEntity> subjects = new ArrayList<SubjectEntity>();
	private List<AnswerEntity> currentAnswerGroup = new ArrayList<AnswerEntity>();
	private Process oThis = this;
	MyApplication myApplication;
	CustomProgressDialog proDialog;// 加载框

	/**
	 * 题目状态标识
	 */
	private boolean isNewSubject = false;
	private boolean hadChosenAnswer = false;

	private int iconOffset = 40;

	/**
	 * 记录题目和选择的答案
	 */
	private Map<String, String> resultmap = new HashMap<String, String>();
	// 记录题号，便于进行跳转
	private List<Map<String, String>> subjList = new ArrayList<Map<String, String>>();
	// 记录没有完成的题号，以便跳转
	private List<Map<String, String>> subjNList = new ArrayList<Map<String, String>>();

	private Button answerButton;
	private TextView titleTextView;
	private Button leftButton;
	private Button rightButton;
	private TextView tv_wcqk; // 完成情况

	private String answeredIndex = "-1";

	/**
	 * 侧滑布局对象，用于通过手指滑动将左侧的菜单布局进行显示或隐藏。
	 */
	private SlidingLayout slidingLayout;

	private LinearLayout content;

	/**
	 * menu按钮，点击按钮展示左侧布局，再点击一次隐藏左侧布局。
	 */
	private ImageButton menuButton;

	private GridView gridView;
	Grideviewmenu gm;
	private TextView nametv, tv;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.process);
		myApplication = (MyApplication) getApplication();
		myApplication.addActivity(this);
		myApplication.getUserRecords().setUsername(myApplication.getAccount());
		myApplication.getUserRecords().setModule("Process@满意度调查");
		UserRecord.getInstance(myApplication.getUserRecords()).init();
		// 设置滑动菜单
		initSliding();
		// 初始化view
		findView();

		// 点击事件
		setOnClick();

		// 获取满意度调查数据
		getDate();
		
		

	}

	private void initSliding()
	{
		menuButton = (ImageButton) findViewById(R.id.menuButton);
		menuButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				
				showBackTip();
			}
		});
		
	}

	private void getDate()
	{
		proDialog = CustomProgressDialog.createDialog(oThis);
		proDialog.setMessage("数据加载中...");
		proDialog.show();
		proDialog.setCanceledOnTouchOutside(false);
		// 这里单开一个线程和后台数据交互
		new Thread(new LoadData()).start();
	}

	private void findView()
	{
		answerButton = (Button) findViewById(R.id.submitButton);
		// titleTextView = (TextView) findViewById(R.id.textpaperTitle);
		progressBar = (ProgressBar) findViewById(R.id.testProgressBar);
		progressBar.setProgress(0);
		// answerButton.setVisibility(View.INVISIBLE);
		leftButton = (Button) findViewById(R.id.leftButton);
		rightButton = (Button) findViewById(R.id.rightButton);
		subjectFilpper = (MyViewFilpper) findViewById(R.id.subjectViewFilpper);
		tv_wcqk = (TextView) this.findViewById(R.id.wcqk);

	}

	// 是否答完判断，如答题记录答案，累加进度条
	private void dealAnswer()
	{

		if (hadChosenAnswer)
		{
			if (isNewSubject)
			{
				hadAnsweredCount++;
				updateProgress(++progressValue);
				answeredIndex += "," + currentSubjectLocation;
				// 记录已完成题目
				Map<String, String> subjMap = new HashMap<String, String>();
				subjMap.put("tmIndex", "第" + String.valueOf(currentSubjectLocation + 1) + "题");
				subjList.add(subjMap);
			}
			String answerids = "";
			for (AnswerEntity ao : currentAnswerGroup)
			{
				if (ao.isSelected())
				{

					answerids += "," + ao.getId();
				}
			}

			resultmap.put((subjects.get(currentSubjectLocation).getId()) + "", answerids.substring(1));

		}

	}

	// 区分完成与未完成的index
	private void decideIndex()
	{
		String[] arrIndex = { "-1" };
		if (!answeredIndex.equals("-1"))
		{
			arrIndex = answeredIndex.substring(1).split(",");
			subjNList.clear();
			for (int i = 0; i < totalSubjectCount; i++)
			{
				boolean isY = false;
				for (int j = 0; j < arrIndex.length; j++)
				{
					if (String.valueOf(i).equals(arrIndex[j]))
					{
						isY = true;
					}
				}
				// 记录未完成题目
				if (!isY)
				{
					Map<String, String> subjMap = new HashMap<String, String>();
					subjMap.put("tmIndex", "第" + String.valueOf(i + 1) + "题");
					subjNList.add(subjMap);
				}
			}
		}
		else
		{
			subjNList.clear();
			for (int i = 0; i < totalSubjectCount; i++)
			{
				Map<String, String> subjMap = new HashMap<String, String>();
				subjMap.put("tmIndex", "第" + String.valueOf(i + 1) + "题");
				subjNList.add(subjMap);
			}

		}
	}

	private void setOnClick()
	{

		// 调查完
		answerButton.setOnClickListener(this);

		leftButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				// 处理答题情况
				dealAnswer();
				// 切换下一题
				subjectFilpper.showPrevious();
				if (hadAnsweredCount == totalSubjectCount)
				{
					rightButton.setVisibility(View.GONE);// 最后一题的时候把下一题隐藏
					answerButton.setVisibility(View.VISIBLE);// 最后一题的时候把确定按钮显示出来
				}

			}
		});

		rightButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				// 处理答题情况
				dealAnswer();
				// 切换下一题
				subjectFilpper.showNext();
				if (hadAnsweredCount == totalSubjectCount)
				{
					rightButton.setVisibility(View.GONE);// 最后一题的时候把下一题隐藏
					answerButton.setVisibility(View.VISIBLE);// 最后一题的时候把确定按钮显示出来
				}
			}
		});
	}

	Handler myHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			int type = msg.getData().getInt("type");
			switch (type)
			{
				case -1:
					proDialog.dismiss();
					Toast.makeText(oThis, msg.getData().getString("msg"), Toast.LENGTH_SHORT).show();
					break;
				case 0:
					proDialog.dismiss();
					fillContent();
					break;
				case 1:
					break;
				case 2:
					break;
				default:
					break;
			}
		}
	};

	class LoadData implements Runnable
	{

		@Override
		public void run()
		{
			// TODO Auto-generated method stub
			Looper.prepare();
			iniData();
			Looper.loop();

		}

	}

	/**
	 * 填充题目
	 * <p>
	 * 目前实现的是，把题目全部从XML文件中读出，保存到subjects引用中。
	 * 题目动态生成，显示样式在R.layout.processitem中设置，由MyViewFilpper显示。
	 * </p>
	 */
	private void iniData()
	{
		try
		{
			Message msg = myHandler.obtainMessage();
			Bundle bundle = new Bundle();
			List<NameValuePair> ls = new ArrayList<NameValuePair>();
			ls.add(new BasicNameValuePair("userid", myApplication.getAccount() == null ? "" : myApplication.getAccount()));
			JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.URLMYD, ls);
			if (json != null)
			{
				if (!json.toString().equals("{\"msg\":\"系统错误！\",\"success\":\"false\"}"))
				{
					if (!json.getString("jsonstr").equals("") && !json.getString("jsonstr").equals("[]"))
					{

						JSONArray jsonAttr = new JSONArray(json.getString("jsonstr"));
						for (int i = 0; i < jsonAttr.length(); i++)
						{
							JSONObject json_tm = jsonAttr.getJSONObject(i);
							SubjectEntity entity = new SubjectEntity();
							entity.setId(Integer.parseInt(json_tm.getString("tmid")));
							entity.setIndex(i);
							entity.setType(Integer.parseInt(json_tm.getString("type")));
							entity.setContent(json_tm.getString("subjectContent"));
							JSONArray js = new JSONArray(json_tm.getString("answers"));
							List<AnswerEntity> lss = new ArrayList<AnswerEntity>();
							for (int j = 0; j < js.length(); j++)
							{
								JSONObject json_da = js.getJSONObject(j);
								AnswerEntity answerEntity = new AnswerEntity();
								answerEntity.setId(Integer.parseInt(json_da.getJSONObject("answer").getString("daid")));
								answerEntity.setContent(json_da.getJSONObject("answer").getString("content") + "" + " ("
										+ json_da.getJSONObject("answer").getString("fz") + "分)");
								lss.add(answerEntity);
							}

							entity.setAnswers(lss);
							subjects.add(entity);
						}
					}
					else
					{
						bundle.putInt("type", -1);
						bundle.putString("msg", "暂无数据");
					}
				}
				else
				{
					bundle.putInt("type", -1);
					bundle.putString("msg", "系统错误");
				}
			}
			else
			{
				bundle.putInt("type", -1);
				bundle.putString("msg", "网络连接失败!");
			}
			msg.setData(bundle);
			myHandler.sendMessage(msg);

		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 设置完成情况
	private void setFinished()
	{
		tv_wcqk.setText(hadAnsweredCount + "/" + totalSubjectCount);

	}

	// 初始化满意度调查题目
	private void fillContent()
	{
		for (SubjectEntity se : subjects)
		{
			++totalSubjectCount;
			LinearLayout item = new LinearLayout(Process.this);
			item.addView(View.inflate(Process.this, R.layout.processitem, null));
			final TextView sContentView = (TextView) item.findViewById(R.id.subjectContent);
			final TextView sIndexView = (TextView) item.findViewById(R.id.subjectIndex);
			final String sContent = se.getContent();

			int fontsize = sContent.length() > getResources().getInteger(R.integer.subjectContentMaxLength) ? getResources()
					.getInteger(R.integer.subjectContentSmallFont) : getResources()
					.getInteger(R.integer.subjectContentNormalFont);
			sContentView.setTextSize(fontsize);

			sContentView.setText(sContent);
			sContentView.setWidth(DisplayUtil.dip2px(this, 480));

			sIndexView.setText(String.format(getResources().getString(R.string.subjectIndex), se.getIndex() + 1));
			sIndexView.setTextSize(fontsize);
			LinearLayout answerLayout = (LinearLayout) item.findViewById(R.id.answerLayout);
			createAnswerView(answerLayout, se.getType(), se.getAnswers());
			subjectFilpper.addView(item);

			// 获取题目完成情况
			decideIndex();
		}
		updateProgress(0);
		subjectFilpper.setTotalItemCounts(totalSubjectCount);
		subjectFilpper.setCallback(oThis);

	}

	/**
	 * 根据题目的类型，创建不同的答案。
	 * 
	 * @param ll
	 *        答案区域的LinearLayout
	 * @param type
	 *        答案类型
	 */
	private void createAnswerView(LinearLayout ll, int type, List<AnswerEntity> answers)
	{
		switch (type)
		{
			case SubjectEntity.SINGLE:
				createRadioGroup(ll, answers);
				break;
			case SubjectEntity.MULTLCHECK:
				createMutilChecked(ll, answers);
				break;
			case SubjectEntity.TRUEORFALSE:
				createTrueOrFalse(ll, answers);
				break;
		}
	}

	/**
	 * 当题目改变时，此方法被调用
	 * <p>
	 * 在此方法中，修改当前题目的答案选择情况。 标识是否为还没回答的题目。
	 * </p>
	 */
	@Override
	public void subjectChange(int location)
	{
		currentSubjectLocation = location;
		hadChosenAnswer = false;
		isNewSubject = true;
		currentAnswerGroup = subjects.get(currentSubjectLocation).getAnswers();
		for (AnswerEntity ao : currentAnswerGroup)
		{
			if (ao.isSelected())
			{
				hadChosenAnswer = true;
				isNewSubject = false;

			}
		}
		if (hadAnsweredCount == totalSubjectCount)
		{
			rightButton.setVisibility(View.GONE);// 最后一题的时候把下一题隐藏
			answerButton.setVisibility(View.VISIBLE);// 最后一题的时候把确定按钮显示出来
		}
	}

	/**
	 * 创建单选答案组
	 * 
	 * @param ll
	 */
	private void createRadioGroup(LinearLayout ll, List<AnswerEntity> answers)
	{
		RadioGroup rg = new RadioGroup(oThis);
		for (int i = 0; i < answers.size(); i++)
		{
			final String answerContent = answers.get(i).getContent();
			final RadioButton aItem = new RadioButton(oThis);
			aItem.setText(answerContent);
			aItem.setTag(i);
			aItem.setButtonDrawable(R.drawable.myradio);
			int fontSize = answers.get(i).getContent().length() > getResources().getInteger(R.integer.answerContentMaxLength) ? getResources()
					.getInteger(R.integer.answerContentNormalFont) : getResources().getInteger(R.integer.answerContentSmallFont);
			aItem.setTextSize(fontSize);
			aItem.setTextColor(getResources().getColor(R.color.textColor));
			aItem.setHeight(DisplayUtil.dip2px(this, 45));
			aItem.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{

					if (hadAnsweredCount == totalSubjectCount)
					{
						rightButton.setVisibility(View.GONE);// 最后一题的时候把下一题隐藏
						answerButton.setVisibility(View.VISIBLE);// 最后一题的时候把确定按钮显示出来
					}
					aItem.setChecked(true);

					for (AnswerEntity ae : currentAnswerGroup)
					{
						ae.setSelected(false);
					}
					currentAnswerGroup.get((Integer) aItem.getTag()).setSelected(true);
					hadChosenAnswer = true;
					// 做题情况
					dealAnswer();
					// 更新题目是否完成index
					decideIndex();
					// 显示完成情况
					setFinished();
					isNewSubject = false;

				}
			});
			rg.addView(aItem);
		}
		ll.addView(rg);
	}

	/**
	 * 创建多项选择答案组
	 * 
	 * @param ll
	 */
	private void createMutilChecked(LinearLayout ll, List<AnswerEntity> answers)
	{
		ll.setOrientation(LinearLayout.VERTICAL);
		for (int i = 0; i < answers.size(); i++)
		{
			final CheckBox item = new CheckBox(this);
			item.setText(answers.get(i).getContent());
			item.setTag(i);
			item.setButtonDrawable(R.drawable.mycheck);
			item.setPadding(iconOffset, 0, 0, 0);
			int fontSize = answers.get(i).getContent().length() > getResources().getInteger(R.integer.answerContentMaxLength) ? getResources()
					.getInteger(R.integer.answerContentNormalFont) : getResources().getInteger(R.integer.answerContentSmallFont);
			item.setTextSize(fontSize);
			item.setTextColor(getResources().getColor(R.color.processTextColor));
			item.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					item.setChecked(item.isChecked());
					hadChosenAnswer = item.isChecked();
					currentAnswerGroup.get((Integer) item.getTag()).setSelected(true);
				}
			});
			ll.addView(item);
		}
	}

	/**
	 * 创建判断题答案组
	 * 
	 * @param ll
	 */
	private void createTrueOrFalse(LinearLayout ll, List<AnswerEntity> answers)
	{
		RadioGroup rg = new RadioGroup(Process.this);
		RadioButton rBtn = null;
		RadioButton wBtn = null;

		for (int i = 0; i < answers.size(); i++)
		{
			final RadioButton rb = new RadioButton(this);
			rb.setTag(i);
			rb.setPadding(55, 15, 0, 20);
			rb.setText(answers.get(i).getContent());
			rb.setTextColor(getResources().getColor(R.color.processTextColor));
			int fontSize = answers.get(i).getContent().length() > getResources().getInteger(R.integer.answerContentMaxLength) ? getResources()
					.getInteger(R.integer.answerContentNormalFont) : getResources().getInteger(R.integer.answerContentSmallFont);
			rb.setTextSize(fontSize);
			if (answers.get(i).isCorrect())
			{
				rBtn = rb;
				rb.setButtonDrawable(R.drawable.radiobutton_yes);
			}
			else
			{
				wBtn = rb;
				rb.setButtonDrawable(R.drawable.radiobutton_no);
			}
			rb.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					rb.setChecked(true);
					hadChosenAnswer = true;
					for (AnswerEntity ae : currentAnswerGroup)
					{
						ae.setSelected(false);
					}
					currentAnswerGroup.get((Integer) rb.getTag()).setSelected(true);
				}
			});
		}
		rg.addView(rBtn);
		rg.addView(wBtn);
		ll.addView(rg);
	}

	/**
	 * 答题按钮 点击答题时，此方法被调用。每回答一题，答题进度条就增加。 当答完全部题目时，会自动跳转到ProfileActivity中，显示
	 * 考卷的简报信息。
	 */
	@Override
	public void onClick(View v)
	{
		// 处理答题
		dealAnswer();
		if (hadAnsweredCount < totalSubjectCount)
		{
			subjectFilpper.showNext();
		}
		else
		{
			String ids = "";
			String tmids = "";
			Set<String> key = resultmap.keySet();
			for (Iterator it = key.iterator(); it.hasNext();)
			{
				tmids = it.next().toString();
				ids += "#" + tmids + "@" + resultmap.get(tmids).toString();
			}
			if (ids.length() > 0)
			{
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("userid", myApplication.getAccount() == null ? "" : myApplication
						.getAccount()));
				params.add(new BasicNameValuePair("resultids", ids.substring(1)));
				JSONObject res = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.URLMYDSAVE, params);
				String saveInfo = "SAVE_NOTSUCCESS";
				if (res != null)
				{
					try
					{
						saveInfo = res.get("saveInfo").toString();
					}
					catch (JSONException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if (saveInfo.equals("SAVE_SUCCESS"))
				{
					Toast.makeText(oThis, "答题成功", Toast.LENGTH_SHORT).show();

					finish();
				}
				else if (saveInfo.equals("SAVE_NOTSUCCESS"))
				{
					Toast.makeText(oThis, "答题保存失败", Toast.LENGTH_SHORT).show();
				}
			}

		}

	}

	/**
	 * 检测按键 <br/>
	 * 当前界面是考试状态，如果退出的话，需要保存考试状态。 检测返回键是否被按下，如果按下，弹出退出提示框，让用户确认是否退出。
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
		{
			showBackTip();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 显示退出提示框
	 */
	private void showBackTip()
	{
		// final AlertDialog alertDialog = new AlertDialog.Builder(Process.this)
		// .setTitle(R.string.exitTitle)
		// .setMessage(R.string.exitTip)
		// .setPositiveButton(R.string.buttonOK,
		// new DialogInterface.OnClickListener() {
		// public void onClick(DialogInterface dialog,
		// int which) {
		// Process.this.finish();
		// }
		// })
		// .setNegativeButton(R.string.buttonCancle,
		// new DialogInterface.OnClickListener() {
		// public void onClick(DialogInterface dialog,
		// int which) {
		// return;
		// }
		// }).create();
		// alertDialog.show();

		final Dialog dialog = new Dialog(this, R.style.MyDialog);

		dialog.setContentView(R.layout.dialog);
		TextView tv_title = (TextView) dialog.findViewById(R.id.title);
		tv_title.setText(R.string.exitTitle);

		TextView tv_message = (TextView) dialog.findViewById(R.id.message);
		tv_message.setText(R.string.exitTip);

		Button left = (Button) dialog.findViewById(R.id.left);
		left.setText(R.string.buttonOK);
		left.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				dialog.dismiss();
				Process.this.finish();
			}
		});

		Button right = (Button) dialog.findViewById(R.id.right);
		right.setText(R.string.buttonCancle);
		right.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				dialog.dismiss();
				// MainActivity.this.finish();

			}
		});
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();
	}

	/**
	 * 更新进度条
	 * 
	 * @param progress
	 */
	private void updateProgress(int progress)
	{
		progressBar.setProgress(Math.round((float) progress / totalSubjectCount * 100));
	}

}
